<template>
  <div>
    <custom-table
      :columns="columns"
      :query="queryParams"
      :row-btn="rowBtn"
      :show-head-btn="['flush','delete']"
      :show-row-btn="['delete']"
      @tap-head-btn="onTapHeadBtn"
      @tap-row-btn="onTapRowBtn"
      @row-dblclick="onRowDbClick"
      v-bind="$attrs"
      v-on="listeners"
      :hide-pk="true"
      ref="curd"
    >
    <template slot="after-head-button">
      <div style="display: flex;">
      <el-upload
    multiple
    :action="fileUrl"
    :headers="headers"
    :limit="limitNum"
    accept=".xls,.xlsx,csv"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-exceed="onExceed"
    :on-success="onSuccess"
    :on-error = "onError"
    :show-file-list="showFileList">
			<!-- <el-button type="primary">导入</el-button> -->
      <el-button :loading="downloadLoadings"  class="filter-item" size="mini" type="primary" icon="el-icon-download">导入租户</el-button>
		</el-upload>
  </div>
    </template>
    <template slot="exportFrame">
    <!-- <el-col :span="11" :xs="12"> -->
       <!-- <div class="searchFrame"> -->
   <el-button :loading="downloadLoading" class="filter-item" type="text" size="mini" icon="el-icon-download" @click="handleDownload">导出</el-button>
    <!-- </div> -->
    <!-- </el-col> -->
    </template>
    </custom-table>
    <!-- <detail
    v-if="repairUserVisible"
    :visible="repairUserVisible"
    @closeDialog="closeDialog"
    :tableData=tableData
    :tableHead="tableHead"
    :title="title"
    ></detail> -->
    <!-- <ceshi v-if="Visible"></ceshi> -->
  <!-- <div v-if="Visible" class="shade1"></div> -->

  <!-- <el-dialog
        title="上传申请单留档"
        :visible.sync="Visible"
        :modal="true"
        :width="dialogWidths"
        top="10vh"
        append-to-body
        @close="closeDialog"
      >
      <Camera :tackPhoto="tackPhoto" @fatherMethod = "removeUser"  :saveText="saveText"  :number="number"></Camera>
  </el-dialog> -->
<!-- </el-dialog> -->
  </div>

</template>

<script>
import tableMixin from '@/utils/mixin/custom-table'
// import PopUp from '@/views/popup/index'
// import detail from './detail'
// import ceshi from './ceshi'
import { showLoading, hideLoading } from '@/utils'

import Camera from '@/components/Camera/index'
// import mock from '@/utils/mixin/mock'
// import PopUp from '@/views/popup/index'
import curd from '@/api/curd'
// var Mock = require('mockjs')
// import { randomNum } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      // repairUserVisible: false,
      Visible: false,
      // tableData: [],
      // tableHead: [],
      dialogWidths: '50%',
      tackPhoto: false,
      // title: '',
      // room_id: '',
      id: '',
      number: 0,
      saveText: '保存并退宿',
      downloadLoading: false,
      listdata: [], // 导出的数据
      columns: [
        { name: '租户名称', field: 'user_id', type: 'tag', format(col, row) { return row.user ? row.user.real_name : '找不到该用户' } },
        { name: '性别', field: 'alone', type: 'tag', format(col, row) {
          if (row.user) {
            switch (row.user.sex) {
              case 1:
                return '男'
              case 2:
                return '女'
              default:
                return '未知'
            }
          } else {
            return '找不到该用户'
          }
        } },
        { name: '手机号', field: 'status_desc', type: 'tag', format(col, row) { return row.user ? row.user.tel : '找不到该用户' } },
        { name: '身份证', field: 'change_time', type: 'tag', format(col, row) { return row.user ? row.user.id_card : '找不到该用户' } },
        { name: '工作单位', field: 'status', type: 'tag', format(col, row) { return row.user ? row.user.word_unit : '找不到该用户' } },
        { name: '小区名称', field: 'room.building_name', type: 'tag' },
        { name: '楼房名称', field: 'room.building_num', type: 'tag' },
        { name: '房间名称', field: 'room_id', type: 'tag', format(col, row) {
          if (row.room) {
            return row.room.name
          } else {
            return '找不到该房间'
          }
        } },
        { name: '房型', field: 'room.roomType.name', type: 'tag' },
        { name: '房租(元)', field: 'room.roomType.amount', type: 'tag' },
        { name: '物业费(元)', field: 'room.roomType.property_price', type: 'tag', format(col, row) {
          return row.tenement_price ? row.tenement_price : row.room.roomType.property_price
        } },
        { name: '水电费(元)', field: 'sex', type: 'tag', format(col, row) {
          return row.ele_water_price ? row.ele_water_price : (row.payRecord ? Number(row.payRecord.electricity_price) + Number(row.payRecord.water_price) + '元' : 0)
        } },
        { name: '入住时间', field: 'start_time', type: 'tag', format(col, row) {
          // return Number(row.payRecord.electricity_price) + Number(row.payRecord.water_price) + '元'
          // var moment = require('moment')
          // var date = row.start_time
          // console.log('moment(date)', date)
          return row.start_time
        } },
        { name: '租期', field: 'lease_mark' },
        { name: '备注', field: 'room_lease_mark', type: 'content' }
      ],
      fileUrl: process.env.VUE_APP_BASE_API + 'v1/attachment/importUserExcel', // 上传文件的域名地址
      limitNum: 1, // 文件上传个数限制
      fileList: [], // 文件列表
      showFileList: false, // 文件列表是否显示,默认不显示
      headers: {
        'Access-Token': getToken(),
        'X-Requested-With': 'XMLHttpRequest'
      },
      downloadLoadings: false
      // [
      //   { name: '名称', field: 'name', type: 'tag', format(col, row) { return row.building_name + row.building_num + row.name } },
      //   // { name: '租户', field: 'nickname', width: 150 },
      //   { name: '房型', field: 'room_type', type: 'tag', format(col, row) { return !row.type_name ? '该房型已被移除，请重新设置' : row.type_name } },
      //   // { name: '公司', field: 'company', width: 150 },
      //   { name: '租金', field: 'roomType.amount', after: '元', type: 'tag' },
      //   { name: '水电费', field: 'payRecord.fee', after: '元', type: 'tag' },
      //   { name: '可住人数', field: 'use_people', type: 'tag', format(col, row) { return !row.type_name ? row.use_people + '/该房型已被移除，请重新设置' : row.use_people + '/' + row.roomType.live_number } },
      //   // { name: '状态', field: 'status', label: true, type: this.checkAuth('change') ? 'switch' : 'tag', opts: {} },
      //   // { name: '状态', field: 'status', label: true, type: 'tag', opts: {} },
      //   { name: '添加时间', field: 'create_time' }
      // ]
    }
  },
  components: {
    // detail,
    // PopUp
    // Camera
  },
  mixins: [
    tableMixin
    // mock
  ],
  computed: {
    rowBtn() {
      return [
        {
          name: '退宿',
          key: 'notice',
          confirm: '是否将{real_name}进行退宿',
          input: [
            { name: '上传退宿申请单', field: 'avatar', type: 'upload_image', opts: { name: 'link' } }
          ]
        }
      ]
    }
  },
  props: {},
  filters: {},
  created() {
    setTimeout(() => {
      console.log('table_$attrs', this.$attrs)
      console.log('table_listeners', this.listeners)
    }, 2000)
  },
  methods: {
    // 文件上传类型
    // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet --- 后缀为 .xlsx
    // application/vnd.ms-excel --- 后缀为 .xls或.csv
    // 文件上传之前的钩子,可以做一些验证或限制
    beforeUpload(file) {
      console.log('beforeUpload', file)
      let regExp = file.name.replace(/.+\./, '')
      let lower = regExp.toLowerCase() // 把大写字符串全部转为小写字符串
      let suffix = ['xls', 'xlsx']
      if (suffix.indexOf(lower) === -1) {
        return this.$message.warning('请上传后缀名为 xls、xlsx 的附件 !')
      }
      this.downloadLoadings = true
      showLoading('导入中...')
      // let isLt2M = file.size / 1024 / 1024 < 2
      // if (!isLt2M) {
      //   return this.$message.error('请上传文件大小不能超过 2MB 的附件 !')
      // }
    },
    // 导入表格格式校验,后端已做验证，这个暂时不需要
    // beforeUpload(file) {
    //   // let regExp = file.name.replace(/.+\./, '');
    //   // let suffix = ['xls', 'xlsx'];
    //   // if (suffix.indexOf(regExp.toLowerCase()) === -1) {
    //   // 	return this.$message.warning('请上传后缀名为 xls、xlsx 的附件 !');
    //   // }
    // },
    // 文件超出个数限制时的钩子
    onExceed(files, fileList) {
      console.log('onExceed-files', files)
      console.log('onExceed-fileList', fileList)
      return this.$message.warning(`只能选择${this.limitNum}个文件,当前共选择了${files.length + fileList.length}个`)
    },
    // 文件上传成功时的钩子
    onSuccess(response, file, fileList) {
      console.log('onSuccess', response)
      console.log('onSuccess', file)
      console.log('onSuccess', response)
      hideLoading()
      this.onTapHeadBtnFlush({})
      this.fileList = []
      this.downloadLoadings = false
    },
    // 文件上传失败时的钩子
    onError() {
      this.fileList = []
      hideLoading()
      this.downloadLoadings = false
    },
    // 导出数据
    handleDownload() {
      console.log('已选择的数据', this.$refs.curd.selection)
      var selection = this.$refs.curd.selection
      var arr = []
      selection.forEach(element => {
        arr.push(element.id)
      })
      var data = { id: arr }
      console.log('获取', data)
      this.downloadLoading = true
      showLoading('导出中...')
      curd('check_in').get('getTenantList', data).then(res => {
        console.log('获取成功', res.data)
        this.listdata = res.data
        this.down(res.data)
      })
    },
    down(rows) {
      // import('@/vendor/Export2Excel').then(excel => {
      // const tHeader = [
      //   '楼名'
      // ]
      // // console.log('data', data)
      // const filterVal = ['building_name']
      const headers = {
        '租户': 'real_name',
        '性别': 'sex',
        '手机号': 'tel',
        '身份证': 'id_card',
        '工作单位': 'word_unit',
        '小区名称': 'housingName',
        '楼房号': 'buildingName',
        '房间号': 'roomName',
        '房型': 'roomTypeName',
        '房租': 'roomTypeAmount',
        '物业费': 'roomTypePropertyPrice',
        '水电费': 'waterElePrice',
        '入住时间': 'start_time'
      }
      // const filename = '对账单明细'
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // excel是引入文件（也就是@/ventor/Export2Excel）的导出对象
        // 获取所有的数据
        // const { rows } = await curd('check_in').index()
        console.log('rows', rows)
        const data = this.formatJson(headers, rows) // 返回的data就是我们转化后的数据
        excel.export_json_to_excel({
          // 要求转出的表头是中文
          header: Object.keys(headers), // 表头 必填
          data, // //具体数据 必填
          filename: '入住信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        this.$notify({
          title: '导出成功',
          // message: '这是一条成功的提示消息',
          type: 'success'
        })
        this.downloadLoading = false
        hideLoading()
        // console.log('excel', excel)
        // 拿到的数据是这种
        //  [{ username: 'xxx', mobile: 'xxx', ... }, { username: 'xxx', mobile: 'xxx', ... }]
        // 要转化的是如下这种
        // header: ['姓名', '手机号', '入职日期', ...]
        // data: [['张三', '138xxxxxxxx', '1992-08-04', ...], ['李四', '135xxxxxxxx', '1992-08-04', ...]]
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        console.log(item)
        return Object.keys(headers).map(k => {
          // if (headers[k] === 'timeOfEntry' || headers[k] === 'correctionTime') {
          //   return formatDate(item[headers[k]]) // 返回格式化之前的时间
          // } else if (headers[k] === 'formOfEmployment') {
          //   return EmployeeEnum.hireType[item.formOfEmployment] ? EmployeeEnum.hireType[item.formOfEmployment] : '未知'
          // }
          return item[headers[k]]
        })
      })
    },

    onTapRowBtnNotice(...e) {
      // var that = this
      console.log('e', e)
      this.id = e[0].id
      console.log('e', e[2].avatar)

      if (e[2].avatar == '') {
        this.$message('您还没有上传退宿申请单')
        return
      }
      // var url = 'http://bwapi.liuchaoai.com/' + e[2].avatar
      var url = e[2].avatar
      this.removeUser(url)
      // var data = {
      //   user_id: e[0].user_id
      // }
      // showLoading()
      // curd('roomLeaseRecord').get('getPaidNumber', data).then(res => {
      //   hideLoading()
      //   console.log('getPaidNumber', res)
      //   this.number = res.data
      //   if (res.data > 0) {
      //     this.Visible = true
      //     this.tackPhoto = false
      //   } else {
      //     this.Visible = true
      //     this.tackPhoto = true
      //   }
      // }, hideLoading)
    },
    // 移除租户
    removeUser(url) {
      var that = this
      var data = {
        id: that.id,
        url: url
      }
      data['room_id'] = this.room_id
      showLoading('退宿中...')
      curd('roomLeaseRecord').post('removeUser', data).then(res => {
        hideLoading()
        console.log('移除结果', res)
        this.Visible = false
        this.tackPhoto = false
        this.onTapHeadBtnFlush({})
      }, hideLoading)
    },

    // 获取用户详情
    // onTapRowBtnDetail(data) {
    //   var that = this
    //   console.log(data)
    //   // that.Visible = true
    //   // showLoading('刷新权限中...')
    //   // setTimeout(function() {
    //   //   console.log('我被点击了')
    //   //   that.repairUserVisible = true
    //   //   hideLoading()
    //   // }, 1500)
    //   that.room_id = data.id
    //   that.tableHead = [
    //     { name: '头像', field: 'avatar', type: 'image' },
    //     { name: '名称呀', field: 'real_name' },
    //     { name: '手机号', field: 'tel' },
    //     { name: '性别', field: 'sex' },
    //     { name: '工作单位', field: 'word_unit' }
    //   ]
    //   // that.title = '房间详情'
    //   showLoading('获取详情中...')
    //   that.curd.get('getLessee', data).then(res => {
    //     hideLoading()
    //     console.log('全部租户', res)
    //     var arr = ({ list: res.data })
    //     that.tableData = arr
    //     this.Visible = true
    //     // this.onTapHeadBtnFlush({})
    //   }, hideLoading)
    // },

    // 弹窗关闭事件
    closeDialog(value) {
      console.log('我是父级，然后我被点击了', value)
      this.tackPhoto = false
    },
    // 弹窗关闭事件
    // dialogClose() {
    //   var data = {
    //     room_id: this.room_id
    //   }
    //   var list = this.list
    //   curd('check_in').get('getRoomDetail', data).then(res => {
    //     console.log('获取成功', res)
    //     var use_people = res.data.use_people
    //     for (const item of list) {
    //       if (item.id == this.room_id) {
    //         item.use_people = use_people
    //       }
    //     }
    //     // this.list = list
    //     // this.$set('list', list)
    //     // this.listdata = res.data
    //     // this.down(res.data)
    //   })
    //   // console.log('弹窗关闭事件', this.room_id)
    // },
    onRowDbClick() {}
    // onLoad() {
    //   Mock.Random.extend({
    //     roomType(date) {
    //       return this.pick(['单间', '一房一厅', '两房一厅', '三房一厅', '豪华套房'])
    //     },
    //     area() {
    //       return randomNum(50, 200)
    //     },
    //     amount() {
    //       return randomNum(500, 2000)
    //     },
    //     buildingName(data) {
    //       return this.pick(['A栋', 'B栋', 'C栋', 'D栋']) + randomNum(1, 999).toString().padStart(3, '0')
    //     },
    //     company() {
    //       return this.pick(['百度', '阿里巴巴', '腾讯', '华为', '小米', '搜狗', '新浪', '网易']) + '公司'
    //     },
    //     roomNo() {
    //       return '琼花湖' + randomNum(1, 10) + '栋' + randomNum(1, 999).toString().padStart(3, '0')
    //     }
    //   })
    //   var data = Mock.mock({
    //     // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
    //     'list|20': [{
    //       // 属性 id 是一个自增数，起始值为 1，每次增 1
    //       'id|+1': 1,
    //       'number': '@roomno',
    //       'nickname': '@cname',
    //       'area': '@area',
    //       'amount': '@amount',
    //       'create_time': '@now',
    //       'status': '启用',
    //       'room_type': '@roomtype',
    //       'name': '@buildingname',
    //       'water_power_amount|1-300': 1,
    //       'company': '@company'
    //     }]
    //   })

    //   console.log('mock', data)

    //   this.setMockData(data)
    // }
  }
}
</script>

<style lang="scss">
.popClass{
  // width: 80%;
  height: 50%;
  top: 200px;
  position: absolute;
  z-index: 2014;
  background-color: white;
}

.shade1{
   position: fixed;
    top: 0px;
    right: 0px;
    left: 0px;
    bottom: 0px;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.1);
    display:block;

    z-index: 2013;
}
.searchFrame{
  display: flex;
  width: 100%;
  align-items: center;
  justify-content:flex-end;
  // padding: 15px;
  // flex-direction: row-reverse;
  // height: 90px;
  // padding-right: 20px;
  // padding: 10px 20px;
}
.searchClass{
  padding: 7px 15px;
  font-size: 12px;
  margin-left: 10px;
  border-radius: 3px;
  margin-right: 20px;
  width: 100px;
  color: #FFFFFF;
  background-color: #1890ff;
}
.filter-item{
  margin-left: 10px;
}
</style>
